﻿using System.Collections.Generic;

namespace JSM.Internal
{
	/// <summary>
	/// Helpful extension methods
	/// </summary>
	internal static class ExtensionMethods
	{
		/// <summary>
		/// Adds an element with the provided key and value to the <see cref="IDictionary{TKey,TValue}"/> if not already existing.
		/// </summary>
		/// <typeparam name="TKey">
		/// The type of keys in the dictionary.
		/// </typeparam>
		/// <typeparam name="TValue">
		/// The type of values in the dictionary.
		/// </typeparam>
		/// <param name="dictionary">
		/// The dictionary to add the provided key and value to.
		/// </param>
		/// <param name="key">
		/// The object to use as the key of the element to add.
		/// </param>
		/// <param name="value">
		/// The object to use as the value of the element to add.
		/// </param>
		/// <returns>
		/// true if the element was added, otherwise false.
		/// </returns>
		public static bool AddIfNotExist<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value)
		{
			if (dictionary == null || dictionary.ContainsKey(key))
				return false;
			dictionary.Add(key, value);
			return true;
		}

		/// <summary>
		/// Adds an item to the <see cref="ICollection{T}"/> if not already existing.
		/// </summary>
		/// <typeparam name="TValue">
		/// The type of the elements in the collection.
		/// </typeparam>
		/// <param name="list">
		/// The collection to add the provided object to.
		/// </param>
		/// <param name="value">
		/// The object to add to the <see cref="ICollection{T}"/>.
		/// </param>
		/// <returns>
		/// true if the element was added, otherwise false.
		/// </returns>
		public static bool AddIfNotExist<TValue>(this ICollection<TValue> list, TValue value)
		{
			if (list == null || list.Contains(value))
				return false;
			list.Add(value);
			return true;
		}

		/// <summary>
		/// Merges a dictionary to an existing dictionary. Already existing keys will be ignored.
		/// </summary>
		/// <typeparam name="TKey">
		/// The type of keys in the dictionary.
		/// </typeparam>
		/// <typeparam name="TValue">
		/// The type of values in the dictionary.
		/// </typeparam>
		/// <param name="dictionary">
		/// The existing dictionary.
		/// </param>
		/// <param name="dictionaryToAdd">
		/// The dictionary to add.
		/// </param>
		public static void AddRange<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, IDictionary<TKey, TValue> dictionaryToAdd)
		{
			if (dictionary == null || dictionaryToAdd == null)
				return;

			foreach (KeyValuePair<TKey, TValue> keyValuePair in dictionaryToAdd)
				dictionary.AddIfNotExist(keyValuePair.Key, keyValuePair.Value);
		}
	}
}
